﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;

using System.ServiceModel.DomainServices.Client;

using LEEAAttendanceControl.Web.Services;
using LEEAAttendanceControl.General;
using LEEAAttendanceControl.Web;

namespace LEEAAttendanceControl.Views
{
    public partial class Users : Page
    {
        LEEAContext context = new LEEAContext();

        public Users()
        {
            InitializeComponent();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            App myApp = (App)Application.Current;

            myApp.ClearEvents();

            myApp.AddEvent += NewUserHandler;
            myApp.EditEvent += EditUserHandler;
            myApp.DeleteEvent += DeleteUserHandler;
        }

        private void UsersDataSource_LoadingData(object sender, LoadingDataEventArgs e)
        {
            e.LoadBehavior = LoadBehavior.RefreshCurrent;
        }

        public void NewUserHandler(object sender, EventArgs e)
        {
            UserEdit newUser = new UserEdit("New User");

            newUser.LoadData(No.Zero);
            newUser.Closed += UserClosed;

            newUser.Show();
        }

        public void EditUserHandler(object sender, EventArgs e)
        {
            UserSummary selectedUser = UsersGrid.SelectedItem as UserSummary;

            UserEdit newUser = new UserEdit("Edit User");

            newUser.LoadData(selectedUser == null ? 0 : selectedUser.ID);
            newUser.Closed += UserClosed;

            newUser.Show();
        }

        public void DeleteUserHandler(object sender, EventArgs e)
        {
            if (UsersGrid.SelectedItem != null)
            {
                if (MessageBox.Show(ApplicationStrings.DeleteMessage, ApplicationStrings.Delete
                    , MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    UsersDataSource.DataView.Remove(UsersGrid.SelectedItem);

                    UsersDataSource.SubmitChanges();
                }
            }
        }

        public void UserClosed(object sender, EventArgs e)
        {
            UsersDataSource.Load();
        }
    }
}
